<template>
  <div class="upload-box">
    <div>
      <el-upload :multiple="false" :show-file-list="false" :http-request="front">
        <template #default>
          <div class="upload-ele" v-if="!frontUrl">
            <el-icon>
              <Plus />
            </el-icon>
            点击上传
          </div>
          <div v-else class="upload-img-preview">
            <img :src="frontUrl" />
          </div>
        </template>
      </el-upload>
      身份证正面照
    </div>
    <div>
      <el-upload :multiple="false" :show-file-list="false" :http-request="back">
        <template #default>
          <div class="upload-ele" v-if="!backUrl">
            <el-icon>
              <Plus />
            </el-icon>
            点击上传
          </div>
          <div v-else class="upload-img-preview">
            <img :src="backUrl" />
          </div>
        </template>
      </el-upload>
      身份证反面照
    </div>
  </div>
</template>

<script setup>
// import { ref, watch } from 'vue';
import upload, { isLegitimate } from "@/utils/uploadFile";
import { compressorImage } from "@/utils/compressorFn";
import { ElMessage } from "element-plus";

const props = defineProps({
  frontUrl: {
    type: String,
    required: true
  },
  backUrl: {
    type: String,
    required: true
  }
});
const emit = defineEmits(["update:frontUrl", "update:backUrl"]);
/**
 * 校验图片格式以及大小
 */
const validateImage = option => {
  const type = ["image/jpg", "image/jpeg", "image/png"];
  const legitimate = isLegitimate(option, type, 500);
  if (legitimate.msg) {
    ElMessage.error(legitimate.msg);
    return false;
  } else {
    return true;
  }
};

/**
 * 身份证正面上传
 */
const front = async option => {
  compressorImage(option, () => {
    if (validateImage(option)) {
      upload(option).then(res => {
        emit("update:frontUrl", res.url);
      });
    }
  });
};
/**
 * 身份证反面上传
 */
const back = async option => {
  compressorImage(option, () => {
    if (validateImage(option)) {
      upload(option).then(res => {
        emit("update:backUrl", res.url);
      });
    }
  });
};
</script>

<style lang="scss" scoped>
.upload-box {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 30px;
  flex: 1;

  > div {
    width: 100%;
    text-align: center;
    color: #3d3d3d;
  }

  .upload-ele {
    background: #f2f3f5;
    height: 144px;
    margin-bottom: 10px;
    padding-top: 40px;
    box-sizing: border-box;
  }

  .upload-img-preview {
    height: 144px;

    img {
      height: 100%;
      width: 100%;
    }
  }

  ::v-deep(.el-upload) {
    display: block;
    color: #c9cdd4;
    text-align: center;

    .el-icon {
      display: block;
      margin: 0 auto 10px;
      font-size: 30px;
    }
  }
}
</style>
